import {w3cwebsocket} from 'websocket';
import {Message} from "message";
const BASE_URL = import.meta.env.VITE_BACKEND_URL.replace('http','ws')
class Socket{
    ws:w3cwebsocket|null = null
    onOpen:Function|null = null
    onMessage:Function|null = null
    sendMessage:Function = (message:Message)=>{
        this.ws!.send(JSON.stringify(message))
        if(!message.group){
            this.onMessage && this.onMessage({data:JSON.stringify(message)})
        }
    }
    connect(userId:string,password:string){
        this.ws = new w3cwebsocket(`${BASE_URL}/websocket/${userId}/${password}`);
        this.ws.onopen = ()=>{
            this.onOpen&&this.onOpen()
        }

        this.ws.onmessage=(event:MessageEvent)=>{
            this.onMessage&&this.onMessage(event)
        }

    }
    close(){
        this.ws.close()
    }






}





export default new Socket();
